package com.pawernode.config;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.amqp.core.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ配置类，用于声明交换机、队列和绑定关系
 */
@Configuration
@ConfigurationProperties(prefix = "my")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RabbitConfig {

    private String exchangeNormalName;
    private String exchangeAlternateName;
    private String queueNormalName;
    private String queueAlternateName;

    /**
     * 创建一个直接交换机
     *
     * @return DirectExchange类型的交换机
     */
    @Bean
    public DirectExchange normalExchange() {
        return ExchangeBuilder // 默认持久化的，默认不自动删除
                .directExchange(exchangeNormalName) // 交换机名称
                .alternate(exchangeAlternateName) // 设置备用交换机exchangeAlternateName
                .build();
    }

    /**
     * 创建一个持久化的队列
     *
     * @return Queue类型的队列
     */
    @Bean
    public Queue queueNormal() {
        return QueueBuilder.durable(queueNormalName).build();
    }

    /**
     * 将队列绑定到直接交换机
     *
     * @param normalExchange 直接交换机
     * @param queueNormal 队列
     * @return Binding类型的绑定关系
     */
    @Bean
    public Binding binding(DirectExchange normalExchange, Queue queueNormal) {
        return BindingBuilder.bind(queueNormal).to(normalExchange).with("info");
    }

    /**
     * 创建一个扇形交换机作为备用交换机
     *
     * @return FanoutExchange类型的交换机
     */
    @Bean
    public FanoutExchange alternateExchange() {
        return ExchangeBuilder.fanoutExchange(exchangeAlternateName).build();
    }

    /**
     * 创建一个备用的持久化队列
     *
     * @return Queue类型的队列
     */
    @Bean
    public Queue alternateQueue() {
        return QueueBuilder.durable(queueAlternateName).build();
    }

    /**
     * 将备用队列绑定到备用交换机
     *
     * @param alternateExchange 备用交换机
     * @param alternateQueue 备用队列
     * @return Binding类型的绑定关系
     */
    @Bean
    public Binding bindingAlternate(FanoutExchange alternateExchange, Queue alternateQueue) {
        return BindingBuilder.bind(alternateQueue).to(alternateExchange);
    }
}
